<?php

if (!isset($_SESSION)) {
    session_start();
}

class checkout extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    protected $configs;

    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('smarty3', '', 'smarty');
        $this->load->model('pushclimb/order_model');
        $this->load->model('admin-planners/setting_model');
        $this->load->model('pushclimb/tour_model');
        $this->tour_model=new tour_model();
        include APPPATH . 'libraries/defu.php';
        $this->order_model = new order_model();
        $this->setting_model = new setting_model();
    }

    public function index() {

        $map2 = $this->setting_model->getByKey("find-us-on-the-map");
        $Data["map2"] = $map2[0];
        $contactinfo = $this->setting_model->getByKey("contact-information");
        $Data["contactinfo"] = $contactinfo[0];

        $this->smarty
                ->assign('_SESSION', $_SESSION)
                ->assign('Data', $Data)
                ->display("pushclimbing/pages/14_checkout");
    }

    function order() {

        $msgs = array();
        if ((!isset($_POST["Name"])) || $_POST["Name"] == "") {
            $msgs[] = "Name does not empty.";
        }
        if ((!isset($_POST["Email"])) || $_POST["Email"] == "") {
            $msgs[] = "Email does not empty.";
        }
        if (isset($_POST["Email"]) && preg_match("/^[0-9a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["Email"]) === 0) {
            $msgs[] = "Email is not valid.";
        }
        if ((!isset($_POST["Phone"])) || $_POST["Phone"] == "") {
            $msgs[] = "Phone does not empty.";
        }
        if ((!isset($_POST["Note"])) || $_POST["Note"] == "") {
            $msgs[] = "Note does not empty.";
        }

        if (count($msgs) > 0) {
            $code = -44;
            $msg = "";
            foreach ($msgs as $m) {
                $msg.="$m<br/>";
            }
        } else {
            if (
                    isset($_SESSION["CART"]["PR"]) ||
                    isset($_SESSION["CART"]["PK"])
            ) {
                $email_content="";
                $orderid = strtoupper( md5( time() .  getIP() ) );
                $Params = array(
                    "ID" => $orderid,
                    "OrderDate" => date("Y-m-d"),
                    "ShipName" => $_POST["Name"],
                    "ShipPhone" => $_POST["Phone"],
                    "ShipNote" => $_POST["Note"],
                    "ShipEmail" => $_POST["Email"]
                );
                $email_content.="Hello <b>".$_POST["Name"]."</b>! Thank you for order at <a href='Pushclimbing.com'>Pushclimbing.com</a>.<br/><br/><br/>";
                $email_content.="Order information.<br/><br/>
                <table>
                    <tr>
                        <td>
                            Order ID
                        </td>
                        <td>
                            $orderid
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Order Date
                        </td>
                        <td>
                            ".date("Y-m-d")."
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Full Name
                        </td>
                        <td>
                            ".$_POST["Name"]."
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Phone
                        </td>
                        <td>
                            ".$_POST["Phone"]."
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Email
                        </td>
                        <td>
                            ".$_POST["Email"]."
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Note
                        </td>
                        <td>
                            ".$_POST["Note"]."
                        </td>
                    </tr>
                </table>
                ";
                $email_content.="<table style='display: inline-block;border-collapse: collapse;'>";
                $email_content.="
                            <tr style='display: table-row;'>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;font-weight:bold'>Items</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;font-weight:bold'>Price</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;font-weight:bold'>Amount</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;font-weight:bold'>Discount</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;font-weight:bold'>Cash</td>
                            <tr>";
                $monney = 0;
                if (isset($_SESSION["CART"]["PR"]))
                    foreach ($_SESSION["CART"]["PR"] as $pr) {
                        $discount = 0;
                        if (isset($_SESSION["Discounts"]) and 
                        !strpos(",".$_SESSION["Discounts"].",",$pr->ProductID )===false
                        and isset($_SESSION["push"]["user"])
                        ){
                            $discount = 10;
                        }
                        $ODParams[] = array(
                            "OrderID" => $orderid,
                            "ProductID" => $pr->ProductID,
                            "UnitPrice" => $pr->UnitPrice,
                            "Quantity" => $pr->NUM,
                            "Discount" => $discount,
                            "Insert" => date("Y-m-d H:i:s")
                        );
                        $mo=$pr->NUM * $pr->UnitPrice * (100 - $discount) / 100;
                        $monney+=$pr->NUM * $pr->UnitPrice * (100 - $discount) / 100;
                        
                        $email_content.="
                            <tr style='display: table-row;'>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$pr->ProductName</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$ $pr->UnitPrice</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$pr->NUM</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$discount %</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$ $mo</td>
                            <tr>";
                    }
                if (isset($_SESSION["CART"]["PK"]))
                    foreach ($_SESSION["CART"]["PK"] as $pk) {
                        $ODParams[] = array(
                            "OrderID" => $orderid,
                            "PackageID" => $pk->ID,
                            "UnitPrice" => $pk->UnitPrice,
                            "Quantity" => $pr->NUM,
                            "Discount" => 0,
                            "Insert" => date("Y-m-d H:i:s")
                        );
                        $mo=$pk->NUM * $pk->UnitPrice;
                        $monney+=$pk->NUM * $pk->UnitPrice;
                        $email_content.="
                            <tr style='display: table-row;'>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$pk->PackageName</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$ $pk->UnitPrice</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$pk->NUM</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>0</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$ $mo</td>
                            <tr>";
                    }
                    
                $email_content.="
                            <tr style='display: table-row;'>
                                <td colspan='4' style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;font-weight:bold'>Total</td>
                                <td style='border: 1px solid #D7D7D7;display: table-cell;padding: 4px 8px;'>$ $monney</td>
                            <tr>";
                $Params["Monney"] = $monney;
                //echo "<pre>", print_r($Params, true), print_r($ODParams, true); //return;
                $this->db->trans_begin();
                $rok = false;
                if ($this->order_model->insert($Params)) {
                    if ($this->order_model->insertDetail($ODParams))
                        $rok = true;
                }
                if ($this->db->trans_status() === FALSE && $rok) {
                    $this->db->trans_rollback();
                    $code = -1;
                    $msg = "Fail. Please try again.";
                } else {
                    $this->db->trans_commit();
                    $code = 1;
                    $msg = "Success. Thank you for checkout.";
                    unset($_SESSION["CART"]);
                    
                    $email_content.="</table><br/><br/><br/>
                        S67-1 Khu Pho, Sky Garden 3 - Phu My Hung - District 7 - Ho Chi Minh City, Vietnam<br/>
                        Phone: (84) 01264722134<br/>
                        THE CLIMBING CLUB (C) 2011<br/>
                    ";
                    $title="Thank you for order at PushClimbing!";
                    $from_name = "Push Climbing";
                    $from_email = "noreply@pushclimbing.com";
                    $headers = "From: $from_name <$from_email>\r\n";
                    $headers.="Content-type: text/html\r\n";
                    $body="<html><body>$email_content</body></html>";
                    $subject = "$title";
                    $to = $_POST["Email"];
                    @mail($to, $subject, $body, $headers);
                    
        
                }
            } else {
                $code = -1;
                $msg = "Your cart is empty.";
            }
        }
        echo json_encode(array("code" => $code, "msg" => $msg));
    }
    function tour(){
        $msgs = array();
        if ((!isset($_POST["TourID"])) || $_POST["TourID"] == "") {
            $msgs[] = "Bad request.";
        }
        if ((!isset($_POST["Name"])) || $_POST["Name"] == "") {
            $msgs[] = "Name does not empty.";
        }
        if ((!isset($_POST["Email"])) || $_POST["Email"] == "") {
            $msgs[] = "Email does not empty.";
        }
        if (isset($_POST["Email"]) && preg_match("/^[0-9a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["Email"]) === 0) {
            $msgs[] = "Email is not valid.";
        }
        if ((!isset($_POST["Phone"])) || $_POST["Phone"] == "") {
            $msgs[] = "Phone does not empty.";
        }
        if ((!isset($_POST["Note"])) || $_POST["Note"] == "") {
            $msgs[] = "Note does not empty.";
        }

        if (count($msgs) > 0) {
            $code = -44;
            $msg = "";
            foreach ($msgs as $m) {
                $msg.="$m<br/>";
            }
        } else {
            $Params=array(
                "Name"=>$_POST["Name"],
                "Email"=>$_POST["Email"],
                "Phone"=>$_POST["Phone"],
                "Note"=>$_POST["Note"],
                "TourID"=>$_POST["TourID"]
            );
            if($this->tour_model->insertOrderTour($Params)){
                $code=1;
                $msg="Success. Thank you for checkout this tour.";
            }else{
                $code=-1;
                $msg="Fail. Cant checkout this tour.";
            }
        }
        echo json_encode(array("code" => $code, "msg" => $msg));
    }
}

